package json_response

import (
	"github.com/gin-gonic/gin"
	"net/http"
)

const (
	CODE_SUCCESS      = 1   //成功 code
	CODE_ERROR        = 0   //失败 code
	CODE_UNAUTHORIZED = 401 //未授权
)

type JsonHttpResponse struct {
	ctx        *gin.Context
	statusCode int
	code       int
	msg        string
	data       any
}

type JsonHttpResponseOption func(response *JsonHttpResponse)

// WithStatusCode http 状态码
func WithStatusCode(code int) JsonHttpResponseOption {
	return func(response *JsonHttpResponse) {
		response.statusCode = code
	}
}

// WithCode 返回 code
func WithCode(code int) JsonHttpResponseOption {
	return func(response *JsonHttpResponse) {
		response.code = code
	}
}

// WithData 返回数据
func WithData(data any) JsonHttpResponseOption {
	return func(response *JsonHttpResponse) {
		response.data = data
	}
}

// WithMsg 返回信息
func WithMsg(msg string) JsonHttpResponseOption {
	return func(response *JsonHttpResponse) {
		response.msg = msg
	}
}

// NewJsonHttpResponse 新建 http json 返回
func NewJsonHttpResponse(ctx *gin.Context, opts ...JsonHttpResponseOption) *JsonHttpResponse {
	entity := &JsonHttpResponse{
		ctx:        ctx,
		statusCode: http.StatusOK,
		code:       CODE_SUCCESS,
		msg:        "",
		data:       gin.H{},
	}
	for _, opt := range opts {
		opt(entity)
	}
	return entity
}

// SetMsg 设置消息
func (jhr *JsonHttpResponse) SetMsg(msg string) *JsonHttpResponse {
	jhr.msg = msg
	return jhr
}

// SetData 设置数据
func (jhr *JsonHttpResponse) SetData(data any) *JsonHttpResponse {
	jhr.data = data
	return jhr
}

// SetCode 设置 code
func (jhr *JsonHttpResponse) SetCode(code int) *JsonHttpResponse {
	jhr.code = code
	return jhr
}

// SetStatusCode 设置 http 状态吗
func (jhr *JsonHttpResponse) SetStatusCode(code int) *JsonHttpResponse {
	jhr.statusCode = code
	return jhr
}

// Send 响应 http
func (jhr *JsonHttpResponse) Send() {
	jhr.ctx.AbortWithStatusJSON(jhr.statusCode, gin.H{
		"msg":  jhr.msg,
		"code": jhr.code,
		"data": jhr.data,
	})
}
